<?php

namespace Bean\Flow;

class RssFlow extends \Bean\Flow\GenericFlow {

	private $_url;
	private $_items;
	private $_user;
	private $_document;
	
	public function __construct( $url ) {
		parent::__construct();
		$this->_url = $url;
	}

	public function getUrl() {
		return $this->_url;
	}

	public function getUser() {
		if( $this->_user === null ) {
			$xpath = new \DOMXpath( $this->getDocument() );
			$this->_user = new RssFlow\User( $xpath->query( '//image' )->item(0) );
		}
		return $this->_user;
	}

	public function getFlowId() {
		return $this->_url;
	}
	
	public function isReadable( \Bean\User $user = null ) {
		return true;
	}
	
	public function isWritable( \Bean\User $user = null ) {
		return false;
	}
	
	public function getDocument() {
		if( $this->_document === null ) {
			$this->_document = new \DOMDocument();
			$this->_document->load( $this->_url );
		}
		return $this->_document;
	}
	
	public function getItems( $i = 0 ) {

		if( !isset($this->_items[$i]) ) {
			$start = (int) $i*self::N_ITEMS_BY_BLOCK + 1;
			$end = $start += self::N_ITEMS_BY_BLOCK;
			$xpath = new \DOMXpath( $this->getDocument() );
			$items = array();
			foreach( $xpath->query( '//item' ) as $item ) {
				$items[] = new RssFlow\Item( $item, $this );
			}
			$this->_items[$i] = $items;
		}
		return $this->_items[$i];
	}
}
